/*
Version: MPL 1.1/GPL 2.0/LGPL 2.1

The contents of this file are subject to the Mozilla Public License Version 
1.1 (the "License"); you may not use this file except in compliance with 
the License. You may obtain a copy of the License at 
http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.

The Original Code is jsLex - JavaScript profiling injection engine.

The Initial Developer of the Original Code is
Robert Buffone.
Portions created by the Initial Developer are Copyright (C) 2007
the Initial Developer. All Rights Reserved.

Contributor(s):

Robert Buffone

Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
*/
package com.nexaweb.jslex.classloader;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Set;

import org.apache.tools.ant.BuildException;

public class ScriptClassLoader {

	private static final String JSLEX_UTIL_CLASS_NAME = "com.jslex.adapter.JsLexUtil";

	private static ScriptClassLoader	_classLoader = null;
	private URLClassLoader				_internalClassLoader = null;
	private Object						_jsLexUtil = null;
	
	/**
	 * Private contrustor creates the class loader and create the util object.
	 * @param urls
	 * @param parentLoader
	 */
	private ScriptClassLoader(URL[] urls, ClassLoader parentLoader){
		_internalClassLoader = URLClassLoader.newInstance(urls, null);
		_jsLexUtil = createJsLexUtils();
		if (_jsLexUtil == null){
			throw new BuildException("JsLexUtil object not defined");
		}
	}
	
	/**
	 * Called to get and instance of the class loader
	 * @return
	 * @throws MalformedURLException 
	 */
	public static ScriptClassLoader getInstance(ClassLoader parentLoader, String jsLexScriptPath) throws MalformedURLException{
		if (_classLoader == null){
			File	scriptFile = new File(jsLexScriptPath);
			_classLoader = new ScriptClassLoader(new URL[]{scriptFile.toURL()}, parentLoader);
		}
		
		return _classLoader;
	}
	
	/**
	 * Create the utility class that is used to interact with the JavaScript engine.
	 * @return
	 */
	public Object createJsLexUtils() throws BuildException{
		try {
			Class clazz = _internalClassLoader.loadClass(JSLEX_UTIL_CLASS_NAME);
			return clazz.newInstance();
		} catch (ClassNotFoundException classNotFoundException) {
			classNotFoundException.printStackTrace();
			throw new BuildException(classNotFoundException);
		} catch (InstantiationException instantiationException) {
			instantiationException.printStackTrace();
			throw new BuildException(instantiationException);
		} catch (IllegalAccessException illegalAccessException) {
			illegalAccessException.printStackTrace();
			throw new BuildException(illegalAccessException);
		} catch (NoClassDefFoundError noClassDefFoundError) {
			noClassDefFoundError.printStackTrace();
			throw new BuildException(noClassDefFoundError);
		}
	}

	
	public Set getCounterFunctionKeys(){
    	try {
			Method	method = _jsLexUtil.getClass().getMethod("getCounterFunctionKeys", null);
			return (Set)method.invoke(_jsLexUtil, null);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null; 
	}
	
	public void clearCounterFunctionKeys(){
    	try {
			Method	method = _jsLexUtil.getClass().getMethod("clearCounterFunctionKeys", null);
			method.invoke(_jsLexUtil, null);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	
	public String getFunctionName(Integer index){
    	try {
			Method	method = _jsLexUtil.getClass().getMethod("getFunctionName", new Class[]{Integer.class});
			return (String)method.invoke(_jsLexUtil, new Object[] {index});
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.getTargetException().printStackTrace();
		}
		return null;
	}
	
	/**
     * Compress the file content using the Dojo compression
     * 
     * @param fileContent
     * @return
     */
    public String compressFile(File sourceFile, int eol, int profileInjectionValue, int compressNames) throws IOException{
    	try {
			Method	method = _jsLexUtil.getClass().getMethod("compressFile", new Class[]{File.class, Integer.class, Integer.class, Integer.class});
			return (String)method.invoke(_jsLexUtil, new Object[] {sourceFile, new Integer(eol), new Integer(profileInjectionValue), new Integer(compressNames)});
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			System.err.println("Error compressing file: " + sourceFile.getAbsolutePath() + ", " + e.getTargetException().getMessage());
		}
		return null;
    }
}
